<?php
/**
 * SFKNews
 * 私房库 www.sifangku.com 教学项目
 *
 * @desc 栏目管理
 * @copyright 私房库 www.sifangku.com 保留所有版权
 * @author 孙胜利 www.sunshengli.com
 * @version 1.01
 *
 **/
namespace Admin\Controller;
use Common\Controller;
use Admin\Model\TypeModel;
use Common\Tree;
if(!defined('SITE')) exit('Access Denied');
class TypeController extends Controller {
	public function __construct(){
		$this->model=new TypeModel();
		parent::__construct();
	}
	public function index(){
		$tree=new Tree($this->model->getAll());
		$this->view->setData('arctype',$tree->getAll());
		$this->view->display();
	}
	public function add(){
		if(!empty($_POST)){
			if($this->model->add($_POST)){
				if(isAjaxRequest()){
					exit('{"status":1,"message":"添加成功."}');
				}
				$this->skip(array(
					'status'=>'success',
					'url'=>'/News/admin.php/type/index',
					'message'=>'添加成功.'
				));
			}else{
				if(isAjaxRequest()){
					exit('{"status":0,"message":"'.$this->model->getError().'"}');
				}
				$this->skip(array(
					'status'=>'danger',
					'url'=>'/News/admin.php/type/add',
					'message'=>$this->model->getError()
				));
			}
		}
		$tree=new Tree($this->model->getAll());
		$this->view->setData('arctype',$tree->getAll());
		$this->view->display();
	}
	public function update(){
		$data=$this->model->select(get('id'));
		if($data===false || count($data)!=1){
			$this->skip(array(
				'status'=>'danger',
				'url'=>'/News/admin.php/type/index',
				'message'=>'栏目不存在.'
			));
		}
		if(!empty($_POST)){
			if($this->model->update($_POST,get('id'))){
				if(isAjaxRequest()){
					exit('{"status":1,"message":"修改成功."}');
				}
				$this->skip(array(
					'status'=>'success',
					'url'=>'/News/admin.php/type/index',
					'message'=>'修改成功.'
				));
			}else{
				if(isAjaxRequest()){
					exit('{"status":0,"message":"'.$this->model->getError().'"}');
				}
				$this->skip(array(
					'status'=>'danger',
					'url'=>'/News/admin.php/type/update/id/'.get('id'),
					'message'=>$this->model->getError()
				));
			}
		}
		$tree=new Tree($this->model->getAll());
		$this->view->setData('arctype',$tree->getAll());
		$this->view->setData('posterity',$tree->getPosterity($data[0]['id'],true));
		$this->view->setData('type',$data[0]);
		$this->view->display();
	}
	public function delete(){
		if(!isAjaxRequest()){
			exit();
		}
		if(!empty($_POST)){
			$data=$this->model->select(post('id'));
			if($data===false || count($data)!=1){
				exit('{"status":0,"message":"栏目不存在."}');
			}
			if($this->model->delete(post('id'))){
				exit('{"status":1,"message":"删除成功."}');
			}else{
				exit('{"status":0,"message":"删除失败."}');
			}
		}
		/*
		var_dump($this->model->delete(24));
		var_dump($this->model->getError());
		*/
	}
	
}